package com.ruoyi.system.service;

import com.ruoyi.system.domain.User;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserService {

    private static final String SECRET_KEY = "7070f0d01e0efe99f22aca00ba63a967";
    private static final long EXPIRATION_TIME = 86400000; // 24 小时

    public Map<String, Object> handleUserLogin(String openid) {
        // 这里可以根据 openid 查询数据库，如果用户不存在则创建新用户
        // 示例中简单返回用户信息和 token
        Map<String, Object> userInfo = new HashMap<>();
        if (openid != null && !openid.isEmpty()) {
            User user = new User();
            user.setOpenid(openid);
            user.setImg("http://subufxkbf.hb-bkt.clouddn.com/6d24d0797a234552a8faf0dac7218fbc.png");
            user.setUsername("眷恋");
            userInfo.put("openid", openid);
            System.err.println(openid);
            userInfo.put("user",user);
            String token = generateToken(openid);
            userInfo.put("token", token);
        } else {
            userInfo.put("user", null);
            userInfo.put("token", null);
        }
        return userInfo;
    }

    private String generateToken(String openid) {
        return Jwts.builder()
               .setSubject(openid)
               .setIssuedAt(new Date(System.currentTimeMillis()))
               .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
               .signWith(SignatureAlgorithm.HS256, SECRET_KEY)
               .compact();
    }
}
